package com.hospital.payment.module.utils;

import com.hospital.payment.module.config.MinioConfig;
import com.hospital.payment.module.exception.MinioException;
import com.hospital.payment.module.exception.enums.MinioExpCode;
import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * MinIO工具类
 * @author yhn
 * @version 1.0
 */
@Component
public class MinioUtils {
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioClient minioClient;
    /**
     * 上传文件到 MinIO
     */
    public String uploadFile(String objectName, InputStream inputStream, long size, String contentType) {
        try {
            ensureBucketExists();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucket())
                    .object(objectName)
                    .stream(inputStream, size, -1)
                    .contentType(contentType)
                    .build();
            minioClient.putObject(args);
            return objectName;
        } catch (Exception e) {
            throw new MinioException(MinioExpCode.UPLOAD_FILE_FAILED);
        }
    }

    /**
     * 删除文件
     */
    public void deleteFile(String objectName) {
        try {
            RemoveObjectArgs args = RemoveObjectArgs.builder()
                    .bucket(minioConfig.getBucket())
                    .object(objectName)
                    .build();
            minioClient.removeObject(args);
        } catch (Exception ignored) {
        }
    }
    /**
     * 获取预签名URL（带有效期）
     * @param objectName 文件对象名
     */
    public String getPresignedUrl(String objectName) {
        try {
            // 判断对象是否存在
            minioClient.statObject(
                    StatObjectArgs.builder()
                            .bucket(minioConfig.getBucket())
                            .object(objectName)
                            .build()
            );
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(minioConfig.getBucket())
                            .object(objectName)
                            .expiry(minioConfig.getExpireMinutes(), TimeUnit.MINUTES)
                            .build()
            );
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 自动创建桶（如果不存在）
     */
    private void ensureBucketExists() throws Exception {
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket( minioConfig.getBucket()).build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucket()).build());
        }
    }
}
